/*
 * Utility.cpp
 *
 *  Created on: 2015年5月18日
 *      Author: chuanjiang.zh@qq.com
 */

#include "Utility.h"
#include "Path.h"

#ifdef WIN32
#include <winsock2.h>
#else
#include <unistd.h>
#include <netdb.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>

#include <sys/types.h>
#include <ifaddrs.h>
#include <iconv.h>

#endif //


Utility::Utility()
{
}

Utility::~Utility()
{
}

std::string Utility::getHostAddr()
{
	std::string ip;
	std::vector< std::string > addrList;
	getHostAddr(addrList);
	if (addrList.size() > 0)
	{
		ip = addrList[0];
	}
	return ip;
}

size_t Utility::getHostAddr(std::vector< std::string >& addrList)
{
	std::string ip;

	char hname[1024];
	int rc = gethostname(hname, sizeof(hname));
	if (rc != 0)
	{
		return 0;
	}

	struct hostent *hostEnt = gethostbyname(hname);
	if (hostEnt == NULL)
	{
		return 0;
	}

	size_t count = 0;
	for (int i = 0; hostEnt->h_addr_list[i] != NULL; ++i)
	{
		struct in_addr* addr = (struct in_addr*) hostEnt->h_addr_list[i];
		char* addrA = inet_ntoa(*addr);
		addrList.push_back(addrA);
		count ++;
	}

	return count;
}

std::string Utility::findFile(const std::string paths[], int size, const char* filename)
{
    std::string filepath;
    for (int i = 0; i < size; i ++)
    {
        filepath = comn::Path::join(paths[i], filename);
        comn::Path::abspath(filepath);
        if (comn::Path::exist(filepath))
        {
            return filepath;
        }
    }
    return std::string();
}

std::string Utility::findExeFile(const std::string paths[], int size, const char* filename)
{
    std::string filepath = findFile(paths, size, filename);
    if (filepath.empty())
    {
        filepath = filename;
    }
    return filepath;
}
